package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.BuildConfig;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.adapter.MyFriendAdapter;
import com.longqinuo.mycarservice.entity.CarFriend;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.view.LruImageCache;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MyNotesFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyNotesFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static RequestQueue queue;
    private static ImageLoader imageLoader;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mEdit;
    private PullToRefreshListView mPullToRefreshListView;
    private MyFriendAdapter mAdapter;
    private List<CarFriend> mList;
    private String imageUrl = "http://image11.m1905.cn/uploadfile/2009/0910/258/20090910040024296.jpg";
    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    private int mPage = 0;
    public MyNotesFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CarFriendFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MyNotesFragment newInstance(String param1, String param2) {
        MyNotesFragment fragment = new MyNotesFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }

    private void init() {
        manager = getActivity().getSupportFragmentManager();
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue, lruImageCache);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_car_friend, container, false);
        initView(view);
        return view;
    }


    private void initView(View view) {

        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mBack.setOnClickListener(this);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mTitle.setText("我的贴子");
        mEdit = (ImageView) view.findViewById(R.id.iv_top_option);
        mEdit.setOnClickListener(this);
        mPullToRefreshListView = (PullToRefreshListView) view.findViewById(R.id.lv_car_friend_list);
        mList = new ArrayList<>();
        initData();
    }

    private void initData() {
        mAdapter = new MyFriendAdapter(getActivity(),mList,imageLoader);
        ListView listView = mPullToRefreshListView.getRefreshableView();
        listView.setAdapter(mAdapter);

        requestImage(1);

        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        mList.clear();
                        requestImage(1);
                        mPullToRefreshListView.onRefreshComplete();
                    }
                }.execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        mList.clear();
                        requestImage(++mPage);
                        mPullToRefreshListView.onRefreshComplete();
                    }
                }.execute();
            }
        });
    }
    public void requestImage(int page) {
        String getUrl = PathUtils.GET_NOTE+"?id="+135+"&page="+ page+"&rows"+10;
        if (BuildConfig.DEBUG) Log.d(">>>>>>geturl>>", getUrl);
        StringRequest request = new StringRequest(getUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (BuildConfig.DEBUG) Log.d(">>>>result_s>>>>", s);
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    int code = jsonObject.getInt("code");
                    if ( code == 0) {
                        JSONArray array = jsonObject.getJSONArray("data");
                        for (int k = 0; k < array.length(); k++) {
                            JSONObject object = array.getJSONObject(k);

                            String imgs = object.getString("imgs");
                            if (BuildConfig.DEBUG) Log.d(">>>imgs>>>", imgs);
                            String[] images = imgs.split(",");
                            List<String> imageList = new ArrayList<>();
                            for (int j = 0; j < images.length; j++) {
                                imageList.add(PathUtils.LOAD_HEADER+images[j]);
                            }
                            int id = object.getInt("id");
                            String content = object.getString("content");
                            String name = object.getString("username");
                            String time = object.getString("createDate");
                            int likeCount = object.getInt("likeCount");
                            CarFriend c = new CarFriend(imageUrl,name,time,content,imageList,"20",true,""+likeCount);
                            mList.add(c);
                        }
                        mAdapter.notifyDataSetChanged();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(request);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_top_back:
                manager.popBackStack();
                break;
            case R.id.iv_top_option:

                mTransaction = manager.beginTransaction();
                mTransaction.add(R.id.ll_main_layout,new PublishPostFragment(),"PublishPost");
                mTransaction.addToBackStack("PublishPost");
                mTransaction.commit();
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
